package com.zkflzl.mianshi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkflzl.mianshi.annotation.FrequencyControl;
import com.zkflzl.mianshi.common.BaseResponse;
import com.zkflzl.mianshi.common.ErrorCode;
import com.zkflzl.mianshi.common.ResultUtils;
import com.zkflzl.mianshi.constant.CommonConstant;
import com.zkflzl.mianshi.constant.RedisConstant;
import com.zkflzl.mianshi.constant.RedisKey;
import com.zkflzl.mianshi.constant.UserConstant;
import com.zkflzl.mianshi.exception.BusinessException;
import com.zkflzl.mianshi.exception.ThrowUtils;
import com.zkflzl.mianshi.mapper.QuestionMapper;
import com.zkflzl.mianshi.mapper.UserMapper;
import com.zkflzl.mianshi.model.dto.question.QuestionListRequest;
import com.zkflzl.mianshi.model.dto.user.UserLoginRequest;
import com.zkflzl.mianshi.model.dto.user.UserQueryRequest;
import com.zkflzl.mianshi.model.dto.user.UserRegisterRequest;
import com.zkflzl.mianshi.model.dto.user.UserUpdateMyRequest;
import com.zkflzl.mianshi.model.entity.User;
import com.zkflzl.mianshi.model.enums.UserRoleEnum;
import com.zkflzl.mianshi.model.vo.LoginUserVO;
import com.zkflzl.mianshi.model.vo.QuestionListVO;
import com.zkflzl.mianshi.model.vo.UserVO;
import com.zkflzl.mianshi.satoken.DeviceUtils;
import com.zkflzl.mianshi.service.MinioService;
import com.zkflzl.mianshi.service.UserService;
import com.zkflzl.mianshi.utils.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBitSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.zkflzl.mianshi.constant.MinioConstant.MAX_AVATAR_SIZE;
import static com.zkflzl.mianshi.constant.MinioConstant.MINIO_BUCKET;
import static com.zkflzl.mianshi.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务实现
 *
 *
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final RedissonClient redissonClient;
    private final QuestionMapper questionMapper;
    private final MinioService minioService;

    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "zkflzl";

    /**
     * 用户随机码放入Redis的过期时间
     */
    public static final int USER_CODE_EXPIRE_TIME = 2;

    @Override
    @FrequencyControl(time = 3, count = 3, target = FrequencyControl.Target.PUBLIC)
    public String getCodeResp(HttpServletRequest request) {
        Object[] objs = this.getCode(IpUtils.getClientIpAddress(request));
        // 获取图片
        BufferedImage image = (BufferedImage) objs[1];
        // 将图片转为Base64字符串
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", baos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder()
                .encodeToString(imageBytes);
    }

    /**
     * 获取随机验证码(放到Redis中存储)
     *
     * @param ip
     * @return
     */
    public Object[] getCode(String ip) {
        // 把旧的验证码删除,生成新的返回
        RedisUtils.del(RedisKey.getKey(RedisKey.USER_REDIS_CODE_PREFIX, ip));
        // 这个根据自己的需要设置对应的参数来实现个性化
        // 返回的数组第一个参数是生成的验证码，第二个参数是生成的图片
        Object[] objs = VerifyCodeUtil.newBuilder()
                .setWidth(120) // 设置图片的宽度
                .setHeight(35) // 设置图片的高度
                .setSize(5) // 设置字符的个数
                .setLines(3) // 设置干扰线的条数
                .setFontSize(30) // 设置字体的大小
                .setTilt(true) // 设置是否需要倾斜
                .setBackgroundColor(Color.WHITE) // 设置验证码的背景颜色
                .build() // 构建VerifyUtil项目
                .createImage(); // 生成图片
        String code = (String) objs[0];
        log.info("code:{}", code);
        RedisUtils.set(RedisKey.getKey(RedisKey.USER_REDIS_CODE_PREFIX, ip), code, USER_CODE_EXPIRE_TIME,
                TimeUnit.MINUTES);
        return objs;
    }

    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest) {
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String code = userRegisterRequest.getCode();
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, code)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 校验验证码
        this.verifyCode(code, IpUtils.getClientIpAddress(ServletUtils.getRequest()));

        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (userAccount.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
            // 3. 插入数据
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            user.setUserAvatar("http://localhost:9005/mianshi/user/avatar/1/1745122574121/13.jpg");
            user.setUserName("面试者");
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    @Override
    public LoginUserVO userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        String code = userLoginRequest.getCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, code)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, code)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 校验验证码
        this.verifyCode(code, IpUtils.getClientIpAddress(ServletUtils.getRequest()));
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        if (Objects.equals(user.getUserRole(), UserConstant.BAN_ROLE)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号已被封禁");
        }
        // 使用 Sa-Token 登录，并指定设备，同端登录互斥
        StpUtil.login(user.getId(), DeviceUtils.getRequestDevice(request));
        StpUtil.getSession()
                .set(USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object loginUserId = StpUtil.getLoginIdDefaultNull();
        if (loginUserId == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
//        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
//        User currentUser = (User) userObj;
//        if (currentUser == null || currentUser.getId() == null) {
//            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
//        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
//        long userId = currentUser.getId();
        User currentUser = this.getById((String) loginUserId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 获取当前登录用户（允许未登录）
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUserPermitNull(HttpServletRequest request) {
        // 先判断是否已登录（基于 Sa-Token 实现）
        Object loginUserId = StpUtil.getLoginIdDefaultNull();
        if (loginUserId == null) {
            return null;
        }
//        // 先判断是否已登录
//        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
//        User currentUser = (User) userObj;
//        if (currentUser == null || currentUser.getId() == null) {
//            return null;
//        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
//        long userId = currentUser.getId();
        return this.getById((String) loginUserId);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        // 基于 Sa-Token 改造
        Object userObj = StpUtil.getSession()
                .get(USER_LOGIN_STATE);
//        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return isAdmin(user);
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue()
                .equals(user.getUserRole());
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        StpUtil.checkLogin();
        // 移除登录态
        StpUtil.logout();
//        if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
//            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
//        }
//        // 移除登录态
//        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVO(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream()
                .map(this::getUserVO)
                .collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        String userAccount = userQueryRequest.getUserAccount();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StringUtils.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.like(StringUtils.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StringUtils.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 添加用户签到记录
     * @param userId 用户 id
     * @return 当前用户是否已签到成功
     */
    @Override
    public boolean addUserSignIn(long userId) {
        LocalDate date = LocalDate.now();
        String key = RedisConstant.getUserSignInRedisKey(date.getYear(), userId);
        // 获取 Redis 的 BitMap
        RBitSet signInBitSet = redissonClient.getBitSet(key);
        // 获取当前日期是一年中的第几天，作为偏移量（从 1 开始计数）
        int offset = date.getDayOfYear();
        // 查询当天有没有签到
        if (!signInBitSet.get(offset)) {
            // 如果当前未签到，则设置
            signInBitSet.set(offset, true);
        }
        // 当天已签到
        return true;
    }

    /**
     * 获取用户某个年份的签到记录
     *
     * @param userId 用户 id
     * @param year   年份（为空表示当前年份）
     * @return 签到记录映射
     */
    @Override
    public List<Integer> getUserSignInRecord(long userId, Integer year) {
        if (year == null) {
            LocalDate date = LocalDate.now();
            year = date.getYear();
        }
        String key = RedisConstant.getUserSignInRedisKey(year, userId);
        // 获取 Redis 的 BitMap
        RBitSet signInBitSet = redissonClient.getBitSet(key);
        // 加载 BitSet 到内存中，避免后续读取时发送多次请求
        BitSet bitSet = signInBitSet.asBitSet();
        // 统计签到的日期
        List<Integer> dayList = new ArrayList<>();
        // 从索引 0 开始查找下一个被设置为 1 的位
        int index = bitSet.nextSetBit(0);
        while (index >= 0) {
            dayList.add(index);
            // 继续查找下一个被设置为 1 的位
            index = bitSet.nextSetBit(index + 1);
        }
        return dayList;
    }

    @Override
    public BaseResponse<Boolean> changePassword(UserUpdateMyRequest userUpdateMyRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userUpdateMyRequest == null, ErrorCode.PARAMS_ERROR);

        String currentPassword = userUpdateMyRequest.getCurrentPassword();
        String newPassword = userUpdateMyRequest.getNewPassword();

        User loginUser = this.getLoginUser(request);

        if (StringUtils.isBlank(userUpdateMyRequest.getCurrentPassword()) ||
                StringUtils.isBlank(userUpdateMyRequest.getNewPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码不能为空");
        }

        // 校验密码是否正确
        // 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + currentPassword).getBytes());
        if (!loginUser.getUserPassword()
                .equals(encryptPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }

        // 新密码加密
        String newEncryptPassword = DigestUtils.md5DigestAsHex((SALT + newPassword).getBytes());
        loginUser.setUserPassword(newEncryptPassword);

        boolean result = this.updateById(loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "修改密码失败");
        }

        // 删除当前用户缓存
        this.userLogout(request);
        return ResultUtils.success(true);
    }

    @Override
    public Page<QuestionListVO> getQuestionUserThumbList(QuestionListRequest questionListRequest, Long userId) {
        int current = questionListRequest.getCurrent();
        int pageSize = questionListRequest.getPageSize();

        Page<QuestionListVO> page = new Page<>(current, pageSize);

        return questionMapper.getQuestionUserThumbList(page, userId);
    }

    @Override
    public Page<QuestionListVO> getQuestionUserFavorList(QuestionListRequest questionListRequest, Long userId) {
        int current = questionListRequest.getCurrent();
        int pageSize = questionListRequest.getPageSize();

        Page<QuestionListVO> page = new Page<>(current, pageSize);

        return questionMapper.getQuestionUserFavorList(page, userId);
    }

    @Override
    public BaseResponse<String> uploadAvatar(MultipartFile file, Long userId, HttpServletRequest request) {
        if (file == null || file.getSize() > MAX_AVATAR_SIZE) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件为空或文件大小超过5MB");
        }
        // 校验图片格式是否符合
        if (MyFileUtils.isNotValidImage(file)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片格式错误");
        }
        String avatarUrl;
        if (userId == null) {
            userId = 0L;
        }
        try {
            avatarUrl = minioService.uploadAvatar(file, userId);
        } catch (Exception e) {
            log.error("上传头像失败");
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "上传头像失败");
        }
        return ResultUtils.success(avatarUrl);
    }

    @Override
    public BaseResponse<String> delAvatar(String userAvatar, Long userId, HttpServletRequest request) {
        if (userId != null) {
            User user = this.getById(userId);
            ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "操作用户不存在");
            // 先更新用户数据再删图像文件
            user.setUserAvatar("");
            try {
                this.updateById(user);
            } catch (Exception e) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR);
            }
        }
        minioService.delFile(MINIO_BUCKET, userAvatar);
        return ResultUtils.success("删除成功");
    }

    /**
     * 校验验证码
     *
     * @param code
     * @param ip
     * @return
     */
    public void verifyCode(String code, String ip) {
        String s = RedisUtils.getStr(RedisKey.getKey(RedisKey.USER_REDIS_CODE_PREFIX, ip));
        // 验证码过期
        ThrowUtils.throwIf(s == null, ErrorCode.VERIFY_CODE_EXPIRED);
        // 验证码错误
        ThrowUtils.throwIf(!code.equalsIgnoreCase(s), ErrorCode.VERIFY_CODE_ERROR);
    }
}






